package com.rjhch.tonglink.server.jms.local_mqcu;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
public class NewJndiTopicExample {

	public static void main(String[] args) {

        ConnectionFactory testConnFactory = null;
        Topic myTopic = null;
        Connection myConn = null;
        Session mySession = null;
        try {
			Properties pro=new Properties();
			pro.setProperty("java.naming.factory.initial", "tongtech.jms.jndi.JmsContextFactory");
			pro.setProperty("java.naming.provider.url", "tlqlocal://localhost/qcu1");
			javax.naming.Context ctx = new javax.naming.InitialContext(pro);
			
			// lookup the topic
            myTopic = (Topic) ctx.lookup("MyTopic");
            
            // lookup the connection factory
            testConnFactory = (ConnectionFactory) ctx.lookup("LocalConnectionFactory");
            myConn = testConnFactory.createConnection();

            mySession = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer myMsgProducer = mySession.createProducer(myTopic);
            MessageConsumer myMsgConsumer = mySession.createConsumer(myTopic);
            MessageConsumer myMsgConsumer2 = mySession.createConsumer(myTopic);
            myConn.start();
            //发送消息
            TextMessage myTextMsg = mySession.createTextMessage();
            myTextMsg.setText("HelloTopicJNDI...");
            System.out.println("发送消息...");
            myMsgProducer.send(myTextMsg);

            //接收消息
            Message msg = myMsgConsumer.receive();
            if (msg != null && msg instanceof TextMessage) {
                TextMessage text = (TextMessage) msg;
                System.out.println("接收到消息: " + text.getText());
            }
            msg = myMsgConsumer2.receive();
            if (msg != null && msg instanceof TextMessage) {
                TextMessage text = (TextMessage) msg;
                System.out.println("接收到消息: " + text.getText());
            }
        } catch (Exception jmse) {
            System.out.println("Exception oxxurred :" + jmse.toString());
            jmse.printStackTrace();
        } finally {
            try {
                if (mySession != null) {
                    mySession.close();
                }
                if (myConn != null) {     
                    myConn.close();
                }
            } catch (Exception e) {
                System.out.println("退出时发生错误。");
                e.printStackTrace();
            }
        }
    
	}
	
}
